package com.abocode.aichat.server.modules;


import com.abocode.aichat.server.channel.ChannelWrapper;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.exception.NotReadyException;
import com.abocode.aichat.server.exception.StanzaException;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.stanza.Stanza;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by franky-15.
 */
public abstract class AbstractModule implements Module<ServerRuntimeContext> {

    private ServerRuntimeContext serverRuntimeContext;
    private List<ModuleHandler> moduleHandlers;
    private Map<String,ModuleHandler> moduleHandlerContext;

    public void setModuleHandlers(List<ModuleHandler> moduleHandlers) {
        if(moduleHandlers==null && moduleHandlers.isEmpty()){
            throw new RuntimeException("moduleHandlers is null");
        }
        moduleHandlerContext=new HashMap();
        for(ModuleHandler moduleHandler:moduleHandlers){
            moduleHandlerContext.put(moduleHandler.module(),moduleHandler);
        }
    }

    @Override
    public String name() {
        return namespace();
    }

    @Override
    public boolean verify(ChannelWrapper channelWrapper, Stanza stanza) {
        if (isChannelReady() == true && channelWrapper.isReady() == false) {
            throw new NotReadyException();
        }
        return name().equals(stanza.name());
    }

    @Override
    public Replies handler(ChannelWrapper channelWrapper, Stanza stanza) {
        boolean flag = verify(channelWrapper, stanza);
        if (!flag) {
            throw new StanzaException("stanza is not same");
        }
        return service(channelWrapper, stanza);
    }

    public ServerRuntimeContext getServerRuntimeContext() {
        return serverRuntimeContext;
    }

    @Override
    public void setRuntimeContext(ServerRuntimeContext serverRuntimeContext) {
        this.serverRuntimeContext = serverRuntimeContext;
    }

    @Override
    public Replies service(ChannelWrapper channelWrapper, Stanza stanza) {
       /* if(moduleHandlers==null && moduleHandlers.isEmpty()){
            throw new RuntimeException("moduleHandlers is empty");
        }*/
        String module=stanza.module();
        ModuleHandler moduleHandler=moduleHandlerContext.get(module);
        if(moduleHandler==null){
            throw new RuntimeException("moduleHandlers is not found");
        }
        return moduleHandler.execute(channelWrapper, stanza,getServerRuntimeContext());
    }

    @Override
    public boolean isChannelReady() {
        return true;
    }
}
